/*
 * Copyright the original author or authors.
 * 
 * Licensed under the MOZILLA PUBLIC LICENSE, Version 1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *	  http://www.mozilla.org/MPL/MPL-1.1.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.milib.display {
	import com.googlecode.milib.base.MLActionClass;
	import com.googlecode.milib.display.service.MLMC;

	import flash.display.MovieClip;

	/**
	 * @author Marek Brun
	 */
	public class MCAnim extends MLActionClass {

		public var mlmc : MLMC;
		private var frameIni : int;
		private var frameEnd : int;

		public function MCAnim(mc:MovieClip, frameIni:*, frameEnd:*) {
			mlmc=MLMC.forInstance(mc);
			this.frameIni=mlmc.getFrameNumberByNumberOrLabelName(frameIni);
			this.frameEnd=mlmc.getFrameNumberByNumberOrLabelName(frameEnd);
			
			//TODO addDeleteWith(mlmc);
		}
		
		override protected function doStart():Boolean {
			MCFramesObserver.forInstance(mlmc.mc).addWatchForFrame(frameEnd, onMCEnterFrameEnd);
			MCFramesObserver.forInstance(mlmc.mc).addWatchForEnterNewFrame(onMCEnterNewFrame);
			mlmc.mc.gotoAndPlay(frameIni);
			return true;
		}
		
		override protected function doFinish():Boolean {
			if(mlmc.mc.currentFrame==frameEnd){
				_isSuccess=true;
				MCFramesObserver.forInstance(mlmc.mc).removeWatchForFrame(frameEnd, onMCEnterFrameEnd);
				MCFramesObserver.forInstance(mlmc.mc).removeWatchForEnterNewFrame(onMCEnterNewFrame);
				return true;
			}else if(mlmc.mc.currentframe<frameIni || mlmc.mc.currentframe>frameEnd){
				_isSuccess=false;
				MCFramesObserver.forInstance(mlmc.mc).removeWatchForFrame(frameEnd, onMCEnterFrameEnd);
				MCFramesObserver.forInstance(mlmc.mc).removeWatchForEnterNewFrame(onMCEnterNewFrame);
				return true;
			}else{
				return false;
			}
		}
		
//****************************************************************************
// EVENTS for MCAnimRunner
//****************************************************************************
		protected function onMCEnterFrameEnd():void {
			mlmc.mc.stop();
			finish();
		}
		
		protected function onMCEnterNewFrame():void {
			if(mlmc.mc.currentFrame<frameIni || mlmc.mc.currentFrame>=frameEnd){
				finish();
			}
		}
		
	}
}
